"""
---------------------------------------------------------------------
- File: system.py
- Date: 2025/11/14
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 系统相关数据库模型
---------------------------------------------------------------------
"""

import uuid
from datetime import datetime
from typing import Optional

from sqlalchemy import Column
# 导入enum类型
from sqlalchemy.sql.sqltypes import Enum as ASEnum
from sqlmodel import Field, JSON, Relationship, SQLModel

from app.schemas.enums import UserStatusEnum, GenderEnum, RoleStatusEnum
from app.schemas.sqlmode_base import IdTimeModel


class Logs(IdTimeModel, table=True):
    """
    API请求日志模型
    """

    __table_args__ = {"comment": "API请求日志"}
    request_id: uuid.UUID = Field(default_factory=uuid.uuid4, index=True, sa_column_kwargs={"comment": "请求唯一ID"})
    ip: str | None = Field(None, max_length=50, sa_column_kwargs={"comment": "请求IP"})
    method: str | None = Field(None, max_length=10, sa_column_kwargs={"comment": "请求方法"})
    url: str | None = Field(None, max_length=200, sa_column_kwargs={"comment": "请求URL"})
    path_params: dict | None = Field(None, sa_column=Column(JSON, comment="路径参数"))
    query_params: dict | None = Field(None, sa_column=Column(JSON, comment="查询参数"))
    request_body: dict | None = Field(None, sa_column=Column(JSON, comment="请求体"))
    status_code: int | None = Field(None, description="响应状态码", sa_column_kwargs={"comment": "响应状态码"})
    response_body: dict | None = Field(None, sa_column=Column(JSON, comment="响应体"))
    process_time: float | None = Field(None, sa_column_kwargs={"comment": "请求耗时（ms）"})

    # 用户外键
    user_id: int | None = Field(
        None, foreign_key="users.id", ondelete="CASCADE", sa_column_kwargs={"comment": "用户ID"}
    )
    # user关系属性
    user: Optional["Users"] = Relationship(back_populates="logs")


class UserRoleLink(SQLModel, table=True):
    """
    用户角色关联表
    """

    __table_args__ = {"comment": "用户角色关联表"}
    user_id: int | None = Field(None, foreign_key="users.id", primary_key=True, sa_column_kwargs={"comment": "用户ID"})
    role_id: int | None = Field(None, foreign_key="roles.id", primary_key=True, sa_column_kwargs={"comment": "角色ID"})


class Users(IdTimeModel, table=True):
    """
    用户模型
    """

    __table_args__ = {"comment": "用户表"}
    user_no: str = Field(index=True, unique=True, max_length=10, sa_column_kwargs={"comment": "编号"})
    hash_password: str = Field(max_length=100, sa_column_kwargs={"comment": "密码"})
    user_name: str = Field(index=True, max_length=50, sa_column_kwargs={"comment": "用户名"})
    nick_name: str = Field(max_length=50, sa_column_kwargs={"comment": "昵称"})
    user_gender: GenderEnum = Field(
        sa_column=Column(
            ASEnum(GenderEnum, values_callable=lambda obj: [e.value for e in GenderEnum]),
            server_default=GenderEnum.MALE,
            comment="性别: M-男, F-女",
        )
    )
    user_email: str = Field(index=True, unique=True, max_length=100, sa_column_kwargs={"comment": "邮箱"})
    user_phone: str = Field(max_length=20, unique=True, sa_column_kwargs={"comment": "手机号"})
    status: UserStatusEnum = Field(
        sa_column=Column(
            ASEnum(UserStatusEnum, values_callable=lambda obj: [e.value for e in UserStatusEnum]),
            server_default=UserStatusEnum.ACTIVE,
            comment="状态: Y-激活, N-禁用",
        )
    )
    last_login: datetime | None = Field(None, sa_column_kwargs={"comment": "最后登录时间"})

    # logs关系属性
    logs: list["Logs"] = Relationship(back_populates="user")
    # roles关系属性
    roles: list["Roles"] = Relationship(back_populates="users", link_model=UserRoleLink)


class Roles(IdTimeModel, table=True):
    """
    角色模型
    """

    __table_args__ = {"comment": "角色表"}

    role_no: str = Field(index=True, unique=True, max_length=10, sa_column_kwargs={"comment": "编号"})
    role_name: str = Field(index=True, max_length=50, sa_column_kwargs={"comment": "名称"})
    role_desc: str = Field(max_length=200, sa_column_kwargs={"comment": "描述"})
    status: UserStatusEnum = Field(
        sa_column=Column(
            ASEnum(RoleStatusEnum, values_callable=lambda obj: [e.value for e in RoleStatusEnum]),
            server_default=RoleStatusEnum.ACTIVE,
            comment="状态: Y-激活, N-禁用",
        )
    )
    # users关系属性
    users: list["Users"] = Relationship(back_populates="roles", link_model=UserRoleLink)
